/**
 * 61. 旋转链表
 * 
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 * 
 * 示例 1：见图T61-1
 * 输入：head = [1,2,3,4,5], k = 2
 * 输出：[4,5,1,2,3]
 * 
 * 示例 2：见图T61-2
 * 输入：head = [0,1,2], k = 4
 * 输出：[2,0,1]
 * 
 * 提示：
 * 链表中节点的数目在范围 [0, 500] 内
 * -100 <= Node.val <= 100
 * 0 <= k <= 2 * 10^9
 * 
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/rotate-list
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * 
 */

package zw;

public class T61 {

	/**
	 * Definition for singly-linked list. public class ListNode { int val; ListNode
	 * next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val,
	 * ListNode next) { this.val = val; this.next = next; } }
	 */
	public ListNode rotateRight(ListNode head, int k) {
		if(head == null || head.next == null) {
			return head;
		}
		int length = 1;
		ListNode lastNode = head;
		while (lastNode.next != null) {
			length++;
			lastNode = lastNode.next;
		}

		int a = k % length;
		a = length - a;
		
		ListNode node = null;

		node = head;
		while (a > 1) {
			node = node.next;
			a--;
		}

		lastNode.next = head;
		head = node.next;
		node.next = null;

		return head;
	}

	public static void main(String[] args) {
		T61 t61 = new T61();
		ListNode head = new ListNode(1);
		head.next = new ListNode(2);
		head.next.next = new ListNode(3);
		head.next.next.next = new ListNode(4);
		head.next.next.next.next = new ListNode(5);

		t61.rotateRight(head, 2);
	}
}

class ListNode {
	int val;
	ListNode next;

	ListNode() {
	}

	ListNode(int val) {
		this.val = val;
	}

	ListNode(int val, ListNode next) {
		this.val = val;
		this.next = next;
	}
}
